package top.yqingyu.trans$client.main;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.yqingyu.common.utils.ThreadUtil;
import top.yqingyu.qymsg.QyMsg;

import java.util.concurrent.ThreadPoolExecutor;


/**
 * @author YYJ
 * @version 1.0.0
 * @date 2022/4/23 19:33
 * @description
 * @modified by
 */
public class SendMsgThread implements Runnable {

    public final ThreadPoolExecutor MSG_POOL = ThreadUtil.createQyFixedThreadPool(2, "SendMsg", null);
    private final TransClient client;
    private static final Logger logger = LoggerFactory.getLogger(SendMsgThread.class);

    private SendMsgThread(TransClient client) {
        this.client = client;
    }

    public static void init(TransClient client) {
        SendMsgThread th = new SendMsgThread(client);
        Thread thread = new Thread(th);
        thread.setName(Thread.currentThread().getName() + "-SendMsg");
        thread.setDaemon(true);
        thread.start();
    }

    @Override
    public void run() {
        while (client.running.get()) {
            try {
                QyMsg msgHeader = client.REQ_MSG_QUEUE.take();
                MSG_POOL.execute(new DealMsgThread(msgHeader, client.getConnection(), client));

            } catch (Exception e) {
                logger.error("", e);
            }

        }
        MSG_POOL.shutdown();
        logger.warn("shutdown");
    }
}
